/**
 * \* Created with IntelliJ IDEA.
 * \* User: 冯若航
 * \* Date: 2021/5/10
 * \* Time: 18:22
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class 二叉搜索树与双向链表 {
    class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }
        public Node(int _val,Node _left,Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }

    Node pre,head;
    public Node treeToDoublyList(Node root) {
        if(root == null) {
            return null;
        }
        dfs(root);
        //第一个节点指向最后一个节点
        head.left = pre;
        pre.right = head;
        return head;
    }
    void dfs(Node cur) {
        if(cur == null) {
            return;
        }
        dfs(cur.left);
        //让头结点指向第一个节点，父节点则指向当前节点
        if(pre != null) {
            pre.right = cur;
        }else {
            head = cur;
        }
        //当前节点的做指针指向父节点
        cur.left = pre;
        pre = cur;
        dfs(cur.right);
    }
}